package kr.lgh.sms_creditcard.Card;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import kr.lgh.sms_creditcard.R;
import kr.lgh.sms_creditcard.BankType.BankInfo;
import kr.lgh.sms_creditcard.BankType.CustomAdapter;
import kr.lgh.sms_creditcard.DB.SQLiteDBHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class CardToList extends Activity {
	ArrayList<String> arType;
	ArrayList<String> arCard = new ArrayList<String>();
	ArrayList<BankInfo> arMonth;
	SQLiteDBHelper dbHelper;
	SQLiteDatabase db;
	Cursor cursor;
	Button btnDate, btnCard, btnSearch, btnAverage;
	ListView list;
	TextView tv_cardTotal;
	CustomAdapter adapter;
	int mYear, mMonth, mDay;
	int mSelect = 0;
	int cSelect = 0;
	int average = 0;
	boolean flag = false;
	String choice;

	final static String sql = "select _name from Category_Table";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cardlist);

		list = (ListView) findViewById(R.id.cardlist);
		btnDate = (Button) findViewById(R.id.s_date);
		btnCard = (Button) findViewById(R.id.s_card);
		btnAverage = (Button) findViewById(R.id.btn_average);
		btnSearch = (Button) findViewById(R.id.s_search);
		tv_cardTotal = (TextView) findViewById(R.id.tv_cardTotal);
		dbHelper = new SQLiteDBHelper(this);
		arType = new ArrayList<String>();
		arCard = dbHelper.checkCardList();
		list.setOnItemClickListener(mListItemClickListener);
		db = dbHelper.getReadableDatabase();

		cursor = db.rawQuery(sql, null);
		cursor.moveToFirst();

		while (!cursor.isAfterLast()) {
			arType.add(cursor.getString(0));
			cursor.moveToNext();
		}

		Calendar cal = new GregorianCalendar();
		mYear = cal.get(Calendar.YEAR);
		mMonth = cal.get(Calendar.MONTH);
		mDay = cal.get(Calendar.DAY_OF_MONTH);
		btnDate.setText(mYear + ". " + (mMonth + 1));

	}

	public void mOnClick(View v) {
		switch (v.getId()) {

		case R.id.s_card:
			new AlertDialog.Builder(this)
					.setTitle("카드사를 선택하시오.")
					.setIcon(R.drawable.card_select)
					.setSingleChoiceItems(
							(String[]) arCard
									.toArray(new String[arCard.size()]),
							mSelect, new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									mSelect = which;
								}
							})
					.setPositiveButton("확인",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int whichButton) {
									if (arCard.size() > 0) {
										choice = arCard.get(mSelect).toString();
										btnCard.setText(choice);
									} else {
										Toast.makeText(getApplicationContext(),
												"설정에서 카드를 등록하세요.",
												Toast.LENGTH_LONG).show();
									}
								}
							}).setNegativeButton("취소", null).show();
			break;

		case R.id.s_date:
			new DatePickerDialog(CardToList.this, mDateSetListener, mYear,
					mMonth, mDay).show();

			break;

		case R.id.s_search:
			average = 0;
			final DecimalFormat df = new DecimalFormat("#,##0");
			Log.d("TAG", "choice : " + choice + " mYear : " + mYear
					+ " mMonth : " + mMonth);
			if (choice != null && mYear != 0 && mMonth != 0) {
				arMonth = new ArrayList<BankInfo>();
				arMonth = dbHelper.cardToList(choice, mYear, mMonth + 1);

				if (arMonth.size() == 0) {
					Toast.makeText(this, "해당항목 없음", Toast.LENGTH_SHORT).show();
				}
				adapter = new CustomAdapter(this, arMonth);
				list.setAdapter(adapter);

				Log.d("TAG", "kb_list 길이 : " + arMonth.size());
				for (BankInfo bank : arMonth) {
					String log = " / date : " + bank.getS_date() + " / time : "
							+ bank.getS_time() + " / money : "
							+ bank.getS_money() + " / place : "
							+ bank.getS_place() + " / card : "
							+ bank.getS_card();
					Log.d("TAG", log);
					average += bank.getS_money();
					Log.d("TAG", "average : " + average);
				}
				
				
				Log.d("TAG", "average : " + average + " / arMonth.size() : "
						+ arMonth.size());
				btnAverage.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {						
						if (!flag) {							
							btnAverage.setText("￦ "
									+ df.format((average) / arMonth.size())
									+ "원 / 일");
							tv_cardTotal.setText("하루 평균 : ");
							flag = true;
						} else {
							btnAverage.setText("￦ " + df.format((average)) + "원");
							tv_cardTotal.setText("월 합계 : ");
							flag = false;
						}
					}
				});

				if (!flag) {
					btnAverage.setText("￦ " + df.format(average)+ "원");
				}

			} else
				Toast.makeText(this, "값을 선택하시오", Toast.LENGTH_SHORT).show();

			break;
		}
	}

	DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;

			String date = mYear + ". " + (mMonth + 1) + ". " + mDay;
			btnDate.setText(date);
		}
	};

	// ListView 각 Item에 대한 이벤트 발생
	OnItemClickListener mListItemClickListener = new OnItemClickListener() {
		
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Log.d("TAG", "onItemClick()");
			TextView tv1, tv2, tv3, tv4, tv5;
			final Button btnChoice;
			Log.d("TAG", "pos : " + position);
			View itemDlg = View.inflate(getApplicationContext(),
					R.layout.listitem_dialog, null);
			tv1 = (TextView) itemDlg.findViewById(R.id.tv1);
			tv2 = (TextView) itemDlg.findViewById(R.id.tv2);
			tv3 = (TextView) itemDlg.findViewById(R.id.tv3);
			tv4 = (TextView) itemDlg.findViewById(R.id.tv4);
			tv5 = (TextView) itemDlg.findViewById(R.id.tv5);
			btnChoice = (Button) itemDlg.findViewById(R.id.btnchoice_category);

			Log.d("TAG", "view");
			final String s_date = ((TextView) view.findViewById(R.id.t_date))
					.getText().toString().split("\n")[0].trim();
			final String s_time = ((TextView) view.findViewById(R.id.t_date))
					.getText().toString().split("\n")[1].trim();

			String t_date = "날 짜 : "
					+ ((TextView) view.findViewById(R.id.t_date)).getText()
							.toString();
			String t_money = "금 액 : "
					+ ((TextView) view.findViewById(R.id.t_money)).getText()
							.toString();
			String t_place = "장 소 : : "
					+ ((TextView) view.findViewById(R.id.t_place)).getText()
							.toString();
			String t_card = "카 드 : "
					+ ((TextView) view.findViewById(R.id.t_card)).getText()
							.toString();
			String t_category = "카테고리 : ";

			Log.d("TAG", "s_date : " + s_date + " / s_time : " + s_time);
			Log.d("TAG",
					"category : " + dbHelper.findToCategory(s_date, s_time));

			int date_end = t_date.length();
			int money_end = t_money.length();
			int place_end = t_place.length();
			int card_end = t_card.length();

			SpannableStringBuilder date_builder = new SpannableStringBuilder(
					t_date);
			date_builder.setSpan(new ForegroundColorSpan(Color.BLACK), 5,
					date_end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			tv1.append(date_builder);

			SpannableStringBuilder money_builder = new SpannableStringBuilder(
					t_money);
			money_builder.setSpan(new ForegroundColorSpan(Color.BLACK), 5,
					money_end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			tv2.append(money_builder);

			SpannableStringBuilder place_builder = new SpannableStringBuilder(
					t_place);
			place_builder.setSpan(new ForegroundColorSpan(Color.BLACK), 5,
					place_end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			tv3.append(place_builder);

			SpannableStringBuilder card_builder = new SpannableStringBuilder(
					t_card);
			card_builder.setSpan(new ForegroundColorSpan(Color.BLACK), 6,
					card_end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
			tv4.append(card_builder);

			tv5.setText(t_category);
			btnChoice.setText(dbHelper.findToCategory(s_date, s_time));
			cSelect = dbHelper.findToCategoryT_id(s_date, s_time);
			
			// 카테고리 버튼을 눌렀을 때 AlertDialog 출력
			btnChoice.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					new AlertDialog.Builder(CardToList.this)
							.setTitle("카테고리를 선택하세요.")
							.setSingleChoiceItems(
									(String[]) arType.toArray(new String[arType
											.size()]), cSelect,
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											cSelect = which;
										}
									})
							.setPositiveButton("확인",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int whichButton) {
											choice = arType.get(cSelect)
													.toString();
											btnChoice.setText(choice);
										}
									}).setNegativeButton("취소", null).show();
				}
			});

			final AlertDialog ad = new AlertDialog.Builder(CardToList.this)
					.setView(itemDlg)
					.setTitle("결재내역")
					.setNegativeButton("취소", null)
					.setPositiveButton("수정완료",
							new DialogInterface.OnClickListener() {
								// 카테고리 내용을 Message_Table에 수정.
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dbHelper.update_Category(choice, cSelect, s_date,
											s_time);
								}
							}).create();
			ad.show();
		}
	};
}
